package com.yc.utils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;


//TODO: java 通过文件内容的魔术字检查文件类型
/**
 * @program: shopping147_cloud
 * @description:
 * @author: zy
 * @create: 2025-07-22 19:35
 */
public class FileTypeValidator {
    // Allowed MIME types
    private static final Set<String> ALLOWED_MIME_TYPES = new HashSet<>(Arrays.asList(
            "image/jpeg",
            "image/png",
            "image/gif",
            "application/pdf",
            "application/msword", // .doc
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .docx
            "application/vnd.ms-excel", // .xls
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" // .xlsx
    ));

    // Allowed file extensions (for double-checking, less reliable than MIME type)
    private static final Set<String> ALLOWED_EXTENSIONS = new HashSet<>(Arrays.asList(
            "jpg", "jpeg", "png", "gif",
            "pdf",
            "doc", "docx",
            "xls", "xlsx"
    ));

    /**
     * Validates if a file's MIME type and extension are allowed.
     * @param contentType The MIME type of the file (from MultipartFile.getContentType())
     * @param filename The original filename (from MultipartFile.getOriginalFilename())
     * @return true if the file type is allowed, false otherwise.
     */
    public static boolean isValidFileType(String contentType, String filename) {
        if (contentType == null || filename == null || contentType.isEmpty() || filename.isEmpty()) {
            return false; // Or throw an IllegalArgumentException
        }
        // 1. Validate MIME type (more reliable)
        if (!ALLOWED_MIME_TYPES.contains(contentType.toLowerCase())) {
            return false;
        }
        // 2. Validate extension (as a secondary check, or if MIME type is generic)
        String fileExtension = getFileExtension(filename);
        if (fileExtension == null || !ALLOWED_EXTENSIONS.contains(fileExtension.toLowerCase())) {
            return false;
        }
        return true;
    }

    private static String getFileExtension(String filename) {
        int dotIndex = filename.lastIndexOf('.');
        if (dotIndex > 0 && dotIndex < filename.length() - 1) {
            return filename.substring(dotIndex + 1);
        }
        return null;
    }
}
